import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue'),
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/Register.vue'),
  },
  {
    path: '/admin',
    component: () => import('@/views/admin/Layout.vue'),
    redirect: '/admin/home',
    children: [
      { path: 'home', component: () => import('@/views/admin/Home.vue') },
      { path: 'user', component: () => import('@/views/admin/User.vue') },
      { path: 'profile', component: () => import('@/views/admin/Profile.vue') },
      {
        path: 'password',
        component: () => import('@/views/admin/Password.vue'),
      },
    ],
  },
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.VUE_APP_BASE_URL,
  routes,
})

router.beforeEach((to, from, next) => {
  const token = store.getters.token
  // 没有token，且访问的不是login与register，跳转到login
  if (!token && to.name !== 'login' && to.name !== 'register') {
    next({ name: 'login' })
  } else {
    next()
  }
})

export default router
